import { reactive, toRefs } from 'vue'

/**
 * table切换分页mixin
 *
 * @param   {fn}  callback  回调函数，切换分页后回调
 */
export default function getSearchMixin(callback) {
  // 参数
  const mixinDef = reactive({
    loading: false,
    queryParam: {}
  })

  // 页码
  const pagination = reactive({
    total: 0,
    current: 1,
    pageSize: 10,
    hideOnSinglePage: true,
    pageSizeOptions: [5, 10, 20, 30, 40, 80, 100],
    showPageSize: true,
    showJumper: true,
    showLessItems: true,
    showTotal: true,
    size: 'small'
  })

  /**
   * 根据pagination计算当前的编号
   *
   * @param   {number}  rowIndex  数据行序号
   */
  const showIndexNo = (rowIndex) => {
    return `${((pagination.current || 1) - 1) * pagination.pageSize + (rowIndex + 1)}`
  }

  /**
   * 切换分页
   *
   * @param   {number}  page  分页
   */
  const handlePageChange = (page) => {
    pagination.current = page
  }

  /**
   * 切换页码，切换后重置分页
   *
   * @param   {number}  pageSize  页码
   */
  const handlePageSizeChange = (pageSize) => {
    pagination.current = 1
    pagination.pageSize = pageSize
  }

  /**
   * 数据变更后事件
   */
  const handleDataChange = (data, { sorter, type }) => {
    if (type === 'sorter') {
      pagination.current = 1
    }

    const sort = sorter?.field
    const order =
      sorter?.direction === 'ascend' ? 'asc' : sorter?.direction === 'descend' ? 'desc' : undefined
    callback && callback({ sort, order })
  }

  /**
   * 查询条件
   */
  const bindSearch = () => {
    pagination.current = 1
    callback && callback()
  }

  /**
   * 重置搜索
   */
  const resetSearch = () => {
    pagination.current = 1
    mixinDef.loading = false
    mixinDef.queryParam = {}
    callback && callback()
  }

  return {
    ...toRefs(mixinDef),
    pagination,
    showIndexNo,
    handlePageChange,
    handlePageSizeChange,
    handleDataChange,
    bindSearch,
    resetSearch
  }
}
